package com.example.treehole.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.treehole.AboutActivity;
import com.example.treehole.App;
import com.example.treehole.CollectActivity;

import com.example.treehole.LoginActivity;

import com.example.treehole.MyCallBackActivity;
import com.example.treehole.MyPostActivity;
import com.example.treehole.base.BaseBindingFragment;
import com.example.treehole.databinding.DialogEditAddressBinding;
import com.example.treehole.databinding.DialogEditAgeBinding;
import com.example.treehole.databinding.DialogEditInfoBinding;
import com.example.treehole.databinding.DialogEditNicknameBinding;
import com.example.treehole.databinding.DialogEditPasswordBinding;
import com.example.treehole.databinding.FragmentMineBinding;
import com.example.treehole.util.Api;
import com.example.treehole.util.HttpUtil;
import com.example.treehole.util.PasswordEncryptor;
import com.example.treehole.util.SomeUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class MineFragment extends BaseBindingFragment<FragmentMineBinding> {
    @Override
    protected void initData() {
        viewBinder.tvAccount.setText(App.user.phone);
        viewBinder.tvNickname.setText(App.user.nickname.isEmpty() ? "待设置" : App.user.nickname);
        loadImage(App.user.face, viewBinder.ivAvatar);
    }


    private void showEditNicknameDialog() {
        DialogEditNicknameBinding binding = DialogEditNicknameBinding.inflate(getLayoutInflater());
        binding.etNickname.setText(App.user.nickname);
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(binding.getRoot()).show();
        binding.tvSure.setOnClickListener(v -> {
            if (binding.etNickname.getText().toString().isEmpty()) {
                toast("昵称不能为空");
                return;
            }
            App.user.nickname = binding.etNickname.getText().toString();
            viewBinder.tvNickname.setText(App.user.nickname);
            alertDialog.dismiss();
            doUpdate();

        });
        binding.tvCancel.setOnClickListener(v -> alertDialog.dismiss());
    }


    private void showEditPasswordDialog() {
        DialogEditPasswordBinding binding = DialogEditPasswordBinding.inflate(getLayoutInflater());
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(binding.getRoot()).show();
        binding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String originPassword = binding.etOriginPassword.getText().toString();
                String newPassword = binding.etNewPassword.getText().toString();
                if (!PasswordEncryptor.encrypt(originPassword).equals(App.user.password)) {
                    toast("原密码错误");
                    return;
                }
                if (newPassword.length()>6) {
                    toast("密码大于6位");
                    return;
                }
                if (newPassword.isEmpty()) return;
                App.user.password = newPassword;
                alertDialog.dismiss();
                doUpdatePassword();
                App.user.password = PasswordEncryptor.encrypt(newPassword);
            }
        });
        binding.tvCancel.setOnClickListener(v -> alertDialog.dismiss());
    }

    private void showEditInfoDialog() {
        DialogEditInfoBinding binding = DialogEditInfoBinding.inflate(getLayoutInflater());
        binding.etNickname.setText(App.user.info);
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(binding.getRoot()).show();
        binding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.user.info = binding.etNickname.getText().toString();
                doUpdate();
                alertDialog.dismiss();

            }
        });
        binding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    private void showEditAddressDialog() {
        DialogEditAddressBinding binding = DialogEditAddressBinding.inflate(getLayoutInflater());
        binding.etNickname.setText(App.user.address);
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(binding.getRoot()).show();
        binding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String address = binding.etNickname.getText().toString();
                if (address.isEmpty()) {
                    toast("地址不能为空");
                    return;
                }
                App.user.address = address;
                doUpdate();
                alertDialog.dismiss();

            }
        });
        binding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void showEditAgeDialog() {
        DialogEditAgeBinding binding = DialogEditAgeBinding.inflate(getLayoutInflater());
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(binding.getRoot()).show();
        binding.etNickname.setText(App.user.age + "");
        binding.tvSure.setOnClickListener(v -> {
            String age = binding.etNickname.getText().toString();
            if (age.isEmpty() || isTwoDigitNumber(age)) {
                App.user.age = Integer.parseInt(age);
                doUpdate();
                alertDialog.dismiss();
            } else {
                toast("年龄最大值99");
            }


        });
        binding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    public static boolean isTwoDigitNumber(String input) {
        return input.matches("\\d{1,2}");
    }

    @Override
    protected void initListener() {

        viewBinder.tvCallBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(requireActivity(), MyCallBackActivity.class));
            }
        });

        viewBinder.llAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AboutActivity.class);
            }
        });


        viewBinder.llEditPassword.setOnClickListener(v -> showEditPasswordDialog());
        viewBinder.llPost.setOnClickListener(v -> startActivity(MyPostActivity.class));
        viewBinder.llNickname.setOnClickListener(v -> showEditNicknameDialog());
        viewBinder.llInfo.setOnClickListener(v -> showEditInfoDialog());
        viewBinder.llAge.setOnClickListener(v -> showEditAgeDialog());
        viewBinder.llAddress.setOnClickListener(v -> showEditAddressDialog());
        viewBinder.llCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(CollectActivity.class);
            }
        });
        viewBinder.llOut.setOnClickListener(v -> {
            App.logout();
            startActivity(new Intent(requireContext(), LoginActivity.class));
            requireActivity().finish();
        });
        viewBinder.ivAvatar.setOnClickListener(v -> new AlertDialog.Builder(requireActivity()).setItems(new CharSequence[]{"相机", "相册"}, (dialog, which) -> {
            if (which == 0) {
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.CAMERA}, 100);
                } else {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePictureIntent, 100);
                }
            } else {
                startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), 101);
            }
        }).show());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                Bundle extras = data.getExtras();
                Bitmap bitmap = (Bitmap) extras.get("data");
                viewBinder.ivAvatar.setImageBitmap(bitmap);
                File file = new File(getActivity().getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
                FileOutputStream stream = null;
                try {
                    stream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    String filePath = file.getAbsolutePath();
                    doUpload(filePath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    toast("头像更换异常");
                }

            } else {
                String filePath = SomeUtil.getImagePath(requireActivity(), data.getData());
                doUpload(filePath);
            }
        }
    }

    private void doUpload(String filePath) {
        showLoading();
        HttpUtil.update(Api.UPLOAD, new File(filePath), new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {
                App.user.face = data;
                loadImage(data, viewBinder.ivAvatar);
                doUpdate();
            }

            @Override
            public void error(String message) {
                display$Toast(message);
            }
        });
    }

    private void doUpdate() {
        showLoading();
        HttpUtil.post(Api.UPDATE_USER, HttpUtil.toJSON(App.user), new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {
                display$Toast(message);

            }

            @Override
            public void error(String message) {
                display$Toast(message);
            }
        });
    }

    private void doUpdatePassword() {
        showLoading();
        HttpUtil.post(Api.USER_UPDATE_PASSWORD, HttpUtil.toJSON(App.user), new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {
                display$Toast(message);

            }

            @Override
            public void error(String message) {
                display$Toast(message);
            }
        });
    }
}
